﻿#ifndef EXCEL_HPP
#define EXCEL_HPP
#include <QFile>
#include <QDebug>
#include <QMessageBox>
#include "excel/ExcelFormat.h"
/* some function... */

inline QVector<QVector<QString>> loadExcel(QString strSheetName)
{
    QVector<QVector<QString>> vecDatas;//获取所有数据

    return vecDatas;
}
// 数据转成QString，一般日志用
inline QString data2QString(QVector<QStringList> &vecDatas)
{
    QString buf="{";
    for (int r = 0; r < vecDatas.size(); ++r) {
        buf+="[";
        for (int c = 0; c < vecDatas[r].size(); ++c) {
            buf+=vecDatas[r][c]+",";
        }
        buf+="],";
    }
    buf+="}";
    return buf;
}
// 保存为xls
inline bool saveXLS(QString filePath, QVector<QStringList> &vecDatas)
{
    QFile::remove(filePath);
    if(vecDatas.isEmpty()) return 0;
    if(vecDatas[0].size()>255){
        if(QMessageBox::No==QMessageBox::warning(NULL, "警告！", "xls最多支持256列，继续可能会崩溃，是否继续？", QMessageBox::Yes|QMessageBox::No))
            return 0;
    }
    ExcelFormat::BasicExcel xls;
    // create sheet 1 and get the associated BasicExcelWorksheet pointer
    xls.New(1);
    ExcelFormat::BasicExcelWorksheet* sheet = xls.GetWorksheet(0);
    ExcelFormat::XLSFormatManager fmt_mgr(xls);
    // Create a table containing an header row in bold and four rows below.
    ExcelFormat::ExcelFont font_bold;
    font_bold._weight = FW_BOLD; // 700
    ExcelFormat::CellFormat fmt_bold(fmt_mgr);
    fmt_bold.set_font(font_bold);
    // 第一行，字段
    int col, row = 0;
    for(col=0; col<vecDatas[0].size(); ++col) {
        ExcelFormat::BasicExcelCell* cell = sheet->Cell(row, col);
        cell->Set(vecDatas[0][col].toStdWString().c_str());
        cell->SetFormat(fmt_bold);
    }
    // 后面的数据
    for (row = 1; row < vecDatas.size(); ++row) {
        for(col=0; col<vecDatas[row].size(); ++col) {
            ExcelFormat::BasicExcelCell* cell = sheet->Cell(row, col);
            cell->Set(vecDatas[row][col].toStdWString().c_str());
        }
    }
    xls.SaveAs(filePath.toStdWString().c_str());
    return QFile::exists(filePath);
}

// 保存为csv
inline bool saveCSV(QString filePath, QVector<QStringList> &vecDatas)
{
    // 保持到文件中
    QFile file(filePath);
    if (!file.open(QIODevice::WriteOnly)) {
        //QMessageBox::warning(this, "错误", "打印数据文件保存失败!");
        return 0;
    }
    QTextStream out(&file);
    // 保存所有数据
    for (int i=0; i<vecDatas.size(); i++) {
        for (int n=0; n<vecDatas[i].size(); n++) {
            out << "\"" << vecDatas[i][n] << "\"" << ((n!=vecDatas[i].size()-1)?",":"");
        }
        out << "\n";
    }
    file.close();
    return 1;
}


#endif // EXCEL_HPP
